package com.hgshop.yudongyang.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.dubbo.config.annotation.Service;

import com.hgshop.yudongyang.dao.UserMapper;
import com.hgshop.yudongyang.domain.Cart;
import com.hgshop.yudongyang.domain.CartVo;
import com.hgshop.yudongyang.domain.HgUser;
import com.hgshop.yudongyang.service.UserService;
@Service
public class UserServiceImpl implements UserService {

	@Resource
	UserMapper userMapper;
	@Override
	public HgUser findUserByUsernameAndPassword(HgUser user) {
		// TODO Auto-generated method stub
		return userMapper.findUserByUsernameAndPassword(user);
	}
	@Override
	public void addCart(CartVo vo) {
		// TODO Auto-generated method stub
		//合并购物车,根据uid和skuid查询数据库中是否有已经存在的购物车
				Cart cart = userMapper.findCartByUidAndSkuid(vo);
				if(cart!=null) {
					
					//取出之前的老价格
					BigDecimal oldSumTotal = cart.getSumTotal();
					//取出新加的数量
					int newNum = vo.getPnum();
					//取出单价
					BigDecimal price = vo.getPrice();
					BigDecimal afterTotal = price.multiply(new BigDecimal(newNum+""));
					
					//计算新总价
					BigDecimal newTotal = oldSumTotal.add(afterTotal);
					//如果有,更新数量和总价
					vo.setSumTotal(newTotal);
					
					userMapper.updateCart(vo);
					
				}else {
					//否则就是添加
					//计算总价格封装到vo对象里
					//总价=单价*数量
					BigDecimal price = vo.getPrice();
					int pnum = vo.getPnum();
					BigDecimal total = price.multiply(new BigDecimal(pnum+""));
					vo.setSumTotal(total);
					vo.setUpdatetime(new Date());
					vo.setCreatetime(new Date());
					userMapper.addCart(vo);
					
				}
	}
	@Override
	public List<Cart> findCartByUid(Integer uid) {
		// TODO Auto-generated method stub
		return userMapper.findCartByUid(uid);
	}

}
